package cn.wangdh.domain.strategy.service.rule.tree.impl;

import cn.wangdh.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import cn.wangdh.domain.strategy.model.vo.StrategyAwardStockKeyVO;
import cn.wangdh.domain.strategy.repository.IStrategyRepository;
import cn.wangdh.domain.strategy.service.armory.IStrategyDispatch;
import cn.wangdh.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.wangdh.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author WDH
 * @description 库存节点
 * @date 2024年10月22日 21:39
 */

@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId,String ruleValue) {
        log.info("规则规律-扣减库存 userId{} strategyId{} awardId{}", userId, strategyId, awardId);
        //扣减库存并对该库存进行一次上锁
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId);
        if (status) {
            //只要扣减库存成功就写入延迟队列，延迟消费更新数据库记录。
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .awardId(awardId)
                    .strategyId(strategyId)
                    .build());

            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue("")
                            .build())
                    .build();
        }

        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
